package com.example.demo.service.imp;

import lombok.extern.log4j.Log4j2;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.example.demo.entity.AlarmPlatform;
import com.example.demo.entity.rep.RuleRep;
import com.example.demo.mapper.RuleMapper;
import com.example.demo.service.SqlSearchService;
import com.example.demo.service.TemplateService;
import com.example.demo.service.WecomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Log4j2
@Service
public class SqlSearchServiceImp implements SqlSearchService {

    @Autowired
    private RuleMapper ruleMapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private TemplateService templateService;

    @Autowired
    private WecomService wecomService;

    /**
     * SQL 搜索数据
     *
     * @param ruleRep
     */
    @Override
    public void searchDataFromSql(RuleRep ruleRep) {

        try {
            log.info("Executing SQL task: " + ruleRep.getName());
            String sql = ruleRep.getSqlContent();

//            初始化空的 webComUrls
            List<String> webComUrls = ruleRep.getAlarmPlatforms().isEmpty() ? Collections.emptyList() : ruleRep.getAlarmPlatforms().stream().map(AlarmPlatform::getConfig).collect(Collectors.toList());
            // 打印当前数据源标识符
            log.info("Current DataSource ID before switch: " + DynamicDataSourceContextHolder.peek());

            // 根据id，只更新执行时间
            ruleMapper.updateLastUpdateTime(ruleRep.getUuid(), System.currentTimeMillis());

            // 使用动态datasource 获取数据
            String dataSourceId = ruleRep.getDatasourceName();
            DynamicDataSourceContextHolder.push(dataSourceId);

            // 再次打印当前数据源标识符
            log.info("Current DataSource ID after switch: " + DynamicDataSourceContextHolder.peek());
            log.info("Executing SQL: " + ruleRep.getName() + sql);
            List<Map<String, Object>> result = jdbcTemplate.queryForList(sql);
            log.info("Execution SQL result: " + result);

            if (!result.isEmpty()) {
                String template = templateService.generateTemplate(ruleRep.getName(), result);
                log.info("Generated template: \n" + template);
                wecomService.notify(webComUrls, template, ruleRep.getIsTest());
            }
        } catch (Exception e) {
            log.error("Error executing task", e);
        } finally {
            // 清除数据源标识符
            DynamicDataSourceContextHolder.clear();
        }
    }
}
